<template>
  <Box title="信息确认" class="info-confirm-wrapper" style="background-color: #e6eefc" v-bind="$attrs">
    <Panel :showClose="false" second class="info-confirm-center-panel">
      <div class="detail-container">
        <div class="loading-box" v-show="pageLoading">
          <a-skeleton active />
        </div>

        <!-- 详情内容部分 -->
        <div class="detail-content">
          <div class="box-video" v-if="activeTabConfig.title == 'AI监测'">
            <a-carousel
              arrows
              :dots="false"
              v-if="activeTabConfig.key == 'aijc' && fileResourcesList && fileResourcesList.length"
            >
              <template #prevArrow>
                <div class="custom-slick-arrow" style="left: 10px; z-index: 1">&lt;</div>
              </template>
              <template #nextArrow>
                <div class="custom-slick-arrow" style="right: 10px">></div>
              </template>
              <div class="carousel-item-content" v-for="i in fileResourcesList" :key="i.filePath">
                <img :src="i.filePath" alt="图片丢失啦" v-if="i.fileContentType == 1" @click="onImgClick(i.filePath)" />
                <video :src="i.filePath" controls v-else></video>
              </div>
            </a-carousel>
            <div class="empty" v-else>
              <Empty emptyData="暂无图片、视频资源" />
            </div>
          </div>

          <div class="list-content">
            <div class="row" v-for="(item, index) in activeTabConfig.detailList" :key="index">
              <div class="text">{{ item.text }}</div>
              <!-- <a-tooltip
                :title="item.render ? item.render(eventDetail, item.key) : $get(eventDetail, item.key)"
                color="#94c5f2"
              > -->
              <div class="value">
                {{ item.render ? item.render(eventDetail, item.key) : $get(eventDetail, item.key) }}
              </div>
              <!-- </a-tooltip> -->
            </div>

            <div class="row xtsb-img" v-if="activeTabConfig.key == 'xtsb'">
              <div class="text">图片</div>
              <div class="value" v-if="fileResourcesList && fileResourcesList.length">
                <img
                  class="value-img"
                  @click="onImgClick(i.filePath)"
                  v-for="i in fileResourcesList"
                  :key="i.filePath"
                  :src="i.filePath"
                  v-show="i.fileContentType == 1"
                />
              </div>
            </div>

            <!-- 气象预警 -->
            <div class="row" v-if="activeTabConfig.title == '气象预警'">
              <div class="text">气象预警文件</div>
              <div class="value" style="color: #1071ff">气象预警文件.pdf</div>
              <div class="btn-box">
                <a-button class="view" @click="viewPdf">查看</a-button>
                <a-button class="download" @click="downloadPdf">下载</a-button>
              </div>
            </div>
          </div>

          <!--  -->
          <div class="transform-wrapper" v-if="activeTabConfig.tranformEvent && activeTabConfig.tranformEvent.length">
            <div class="transform-title">选择转化的事件类型</div>
            <!-- activeTabConfig.tranformEvent && activeTabConfig.tranformEvent.length -->
            <div class="transform-switch">
              <a-button
                class="transform-button"
                v-for="(item, index) in activeTabConfig.tranformEvent"
                v-show="item"
                :key="index"
                @click="changeTab(item)"
                :class="transformEvent.value == item.value ? 'active' : ''"
              >
                {{ item.name }}
              </a-button>
            </div>
          </div>

          <!-- 表单部分 -->
          <div>
            <div class="form-item-box" v-if="activeTabConfig.showSelect">
              <div class="label" :style="computedFormLabelStyle">拥堵原因</div>
              <a-select class="form-item" v-model:value="congestionCause">
                <a-select-option
                  :key="item.dictItemValue"
                  :value="item.dictItemValue"
                  v-for="item in getDict('ZNZC-CONGESTION')"
                  >{{ item.dictItemdesc }}</a-select-option
                >
              </a-select>
            </div>
            <!-- 备注部分 -->
            <div class="form-item-box" v-if="activeTabConfig.showInput">
              <div class="label" :style="computedFormLabelStyle">备注</div>
              <a-input class="form-item" v-model:value="noteText" placeholder="请输入信息备注或核实到的新事件" />
            </div>
          </div>
        </div>

        <!-- 表单操作部分 -->
        <div class="operates-wrapper" v-if="Array.isArray(activeTabConfig.operates) && activeTabConfig.operates.length">
          <div class="operates-content">
            <a-button
              v-for="item in activeTabConfig.operates"
              :disabled="item.key === 'confirm' && confrimDisabled"
              @click="handleOperates(item)"
              :class="`${item.className} ${item.key === 'confirm' && confrimDisabled && 'is-disabled'}`"
              :key="item.className"
            >
              {{ item.text }}
            </a-button>
          </div>
        </div>
      </div>

      <!-- 模态框部分 -->
      <ModelPanel
        :visible="modelState.visible"
        :afterClose="modelAfterClose"
        :title="modelState.title"
        class="tips-model"
        ref="modelPanel"
        :showClose="false"
        @handleOk="handleOk"
        @cancel="cancel"
      >
        <div class="model-content">
          <!-- 忽略内容 -->
          <div class="tip-text" v-if="currentOperatesConfig.operateType === ignoreType">确认忽略吗?</div>

          <!-- 误报内容 -->
          <div v-else-if="currentOperatesConfig.operateType === misstateType">
            <a-textarea
              class="textarea"
              v-model:value="modelState.ignoreValue"
              :rows="2"
              placeholder="请输入说明  （ 选填）"
            />
          </div>

          <!-- 确认事件内容 -->
          <div class="tip-text" v-else-if="currentOperatesConfig.operateType === confirmType">
            <!-- 事件已核实完毕，确认后即到右屏进行事件处置-->
            事件已核实完毕
          </div>
        </div>
      </ModelPanel>

      <!-- 关联表格 -->
      <RelationEvent
        :transformEvent="transformEvent"
        v-if="isShowRelation"
        :detectionType="activeTabConfig.type"
        :alarmType="eventDetail.alarmType"
        class="relation-event-container"
        @close="close"
      ></RelationEvent>
    </Panel>

    <!-- 显示放大的图片 -->
    <a-modal
      :width="510"
      :visible="imgVisible"
      :destroyOnClose="true"
      :footer="false"
      :closable="false"
      class="intelligent-model"
      @cancel="imgVisible = false"
    >
      <img class="over-view-img" :src="imgUrl" />
    </a-modal>
  </Box>
</template>

<script>
/** * @des: 智能侦测--信息确认 * @author: 刘清华 * @date: 2022/11/2 */

export default {
  name: 'IntelligentDetail'
}
</script>

<script setup>
import Box from '../../components/detail/Box.vue'
import * as intelligentApi from '@/views/business-component/api/intelligent.js'
import baseServiceApi from '../../api/base-service'
import { useStore } from 'vuex'
import Empty from '../../components/empty'
import { ref, watch, getCurrentInstance, computed, reactive, nextTick, shallowRef } from 'vue'
import { confirmType, misstateType, ignoreType } from '../../config/intelligent'
import RelationEvent from './RelationEvent.vue'
import Panel from '../../components/panel'
import { useObjectUrl } from '@vueuse/core'
import { saveAs } from 'file-saver'
import ModelPanel from '../../components/model-panel'
import { message } from 'ant-design-vue'
import { get } from '@/utils'
import config from '@/config'
import { getDict } from '@/core/dictionaries'

const file = shallowRef()
const blobObjectUrl = useObjectUrl(file)
const { proxy } = getCurrentInstance()
const $get = proxy.$get
const store = useStore()
const intelligentData = computed(() => store.state.config.detailConfig.data)
const roadType = computed(() => store.state.config.roadType)
const fileResourcesList = ref([])
const modelPanel = ref() // 模态框ref对象
const activeTabConfig = ref({}) // 当前选中的tab配置
const eventDetail = ref({}) // 事件详情
const currentOperatesConfig = ref({})
const isShowRelation = ref(false) // 显示关联事件
const pageLoading = ref(false)

// 保存图片路径
const imgUrl = ref('')
// 控制图片放大弹出框显示隐藏
const imgVisible = ref(false)

// 当前选中转换事件
const transformEvent = ref({})

// 模态框状态
const modelState = reactive({
  visible: false,
  title: null,
  item: {},
  ignoreValue: ''
})

// 拥堵原因下拉框
const congestionCause = ref(null)
// 备注input内容
const noteText = ref(null)
// 禁用确认核实状态
const confrimDisabled = ref(false)

const computedFormLabelStyle = computed(() => {
  if (!activeTabConfig.value.showInput || !activeTabConfig.value.showSelect) {
    return {
      width: 'auto'
    }
  }
  return {}
})

// 监听detailConfig 变化
watch(
  () => store.state.config.detailConfig,
  (newValue, oldValue) => {
    nextTick(() => {
      if (newValue.type === 'intelligent') {
        activeTabConfig.value = newValue.actions || {}
        confrimDisabled.value = false
        if (Array.isArray(activeTabConfig.value.tranformEvent) && activeTabConfig.value.tranformEvent.length) {
          transformEvent.value = activeTabConfig.value.tranformEvent[0]
          confrimDisabled.value = activeTabConfig.value.tranformEvent[0].confirmDisabeld
        } else {
          transformEvent.value = {}
        }

        getDetail(newValue.data)
      }
    })
  },
  {
    deep: true,
    immediate: true
  }
)

/**
 * 获取详情
 * @param  detail { Object }
 */
function getDetail(detail) {
  noteText.value = null
  fileResourcesList.value = []
  congestionCause.value = null
  pageLoading.value = true
  file.value = null
  eventDetail.value = detail
  setTimeout(() => {
    pageLoading.value = false
  }, 500)

  if ((detail.fileModelList || []).length) {
    if (activeTabConfig.value.key === 'aijc' && roadType.value == 1) {
      return getAIStarm(detail.fileModelList)
    }
    baseServiceApi.getSofFileConnection(detail.fileModelList).then(res => {
      if (res.data && res.data.length) {
        fileResourcesList.value = res.data
      }
    })
  }
  // intelligentApi.getDetectidetail(detail.detectionId)
  //   .then(res => {
  //     const data = res.data || {}
  //     eventDetail.value = data || {}

  //     // 拉取气象预警的文件
  //     if (activeTabConfig.value.title === '气象预警' && data.fileModels && data.fileModels.length) {
  //       qxyJObjectUrl(data)
  //     }
  //   })
  //   .catch(() => {
  //     $message.error('获取详情失败')
  //   })
  //   .finally(() => (pageLoading.value = false))
}

/**
 * 切换事件tab切换
 */

function changeTab(item) {
  transformEvent.value = item
  confrimDisabled.value = item.confirmDisabeld
}

/**
 * 信息确认底部操作
 *
 */
function handleOperates(itemConfig) {
  // 没有确认类型就是关联事件
  if (!itemConfig.operateType) {
    isShowRelation.value = true
    return // 关联事件
  }
  isShowRelation.value = false
  console.log('itemConfig', itemConfig)
  console.log('activeTabConfig', activeTabConfig)
  console.log('transformEvent', transformEvent)

  modelState.title = itemConfig.text
  currentOperatesConfig.value = itemConfig

  if (itemConfig.operateType === confirmType) {
    if (activeTabConfig.value.title === '交通态势' && !congestionCause.value) {
      return message.error(`核实失败,请选择拥堵原因`)
    }
  }

  modelState.visible = true
}

/**
 * 模态框的确认回调
 *
 * **/
function handleOk() {
  const params = {
    detectionId: intelligentData.value.detectionId || eventDetail.value.detectionId, // 智能侦测Id
    unit: store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgId : '',
    operator: store.state.user.userInfo.userId, // 操作人
    userName: store.state.user.userInfo.name,
    detectionType: activeTabConfig.value.type, //  智能侦测类型
    // desc: null, // 智能侦测描述
    // eventSource: roadType.value === 2 ? '2' : eventDetail.value.detectionClassify + 20, //  事件来源  公路2其他系统转入 1高速 +20是因为事件处置占用了字典的key
    eventSource: eventDetail.value.detectionClassify + 20, //  信息来源
    happenTime: intelligentData.value.monitorTime, //  发生时间
    endTime: null, //  结束时间
    roadSysType: roadType.value, //  事件环境变量 2公路 1高速
    roadNum: intelligentData.value.roadNum, // 路线编号
    roadName: intelligentData.value.roadName, // 路线名称
    from: intelligentData.value.startPile, // 开始桩号
    to: intelligentData.value.endPile, // 结束桩号
    projectCode: config.appCode, // 项目标识说明
    customEventType: transformEvent.value.value, // 说明自定义事件
    administrativeCode: '', // 地市编码
    path: JSON.stringify(intelligentData.value.path), // 经纬度集合
    roadDirection: intelligentData.value.roadDirection, //  方向
    companyType: $get(store.state, 'user.bussinessType'),
    // ignoreType: null, //  忽略误报状态 3:误报4:忽略   ... 1:确认事件;2:关联事件
    // ignoreDesc: null, //  忽略误报描述
    companyName: store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgName : '',
    remark: noteText.value,
    alarmType: eventDetail.value.alarmType, //  告警类型
    detectionSituationRequest: {
      districtId: '', // 省市区编码
      distance: intelligentData.value.jamDistance, // 拥堵距离
      duration: intelligentData.value.duration, // 预计通行时间
      amReason: congestionCause.value
    } //  列表项对象
    // 误报才有 desc
  }
  //  忽略 误报  确认事件
  if ([misstateType, ignoreType, confirmType].includes(currentOperatesConfig.value.operateType)) {
    let funName = null

    if (confirmType !== currentOperatesConfig.value.operateType) {
      //  忽略 误报 相关参数
      params.ignoreType = currentOperatesConfig.value.text === '忽略' ? ignoreType : misstateType
      params.ignoreDesc = currentOperatesConfig.value.text === '误报' ? modelState.ignoreValue : null
      funName = 'operateMisinformationIgnore'
    } else {
      // 确认事件 相关参数
      params.ignoreType = confirmType
      params.eventType = transformEvent.value.eventType
      params.eventAttribute = transformEvent.value.eventAttribute
      funName = 'operatesDetectionConfirm'
    }

    intelligentApi[funName](params)
      .then(res => {
        // 确认的返回

        if (currentOperatesConfig.value.operateType === confirmType) {
          if (res.data) {
            message.success('操作成功')
            cancel()

            nextTick(() => {
              proxy.$bus.emit('overGetList', intelligentData.value.detectionId)
            })
          } else {
            modelPanel.value.confrimLoaing = false
            message.error('操作失败')
          }
          return
        }

        // 忽略 误报  的返回
        if (res.code == 200) {
          message.success('操作成功')
          cancel()

          nextTick(() => {
            proxy.$bus.emit('overGetList', intelligentData.value.detectionId)
          })
        } else {
          modelPanel.value.confrimLoaing = false
          message.error('操作失败')
        }
      })
      .catch(() => {
        modelPanel.value.confrimLoaing = false
        message.error('操作失败')
      })
  }
}

function cancel() {
  modelState.visible = false
}

/**
 * @desc
 * 模态框关闭后的回调
 * **/
function modelAfterClose() {
  modelState.ignoreValue = null
}

/** *
 * @desc  关闭关联事件
 * ***/
function close() {
  isShowRelation.value = false
}

/**
 * @desc 处理气象预警查看pdf文件
 * **/
function qxyJObjectUrl(data) {
  intelligentApi
    .downloadFile({
      filePath: data.fileModels[0].fileName
    })
    .then(res => {
      file.value = new Blob([res], { type: 'application/pdf' })
    })
}
/**
 * @desc 处理气象预警查看pdf
 *
 * **/
function viewPdf() {
  blobObjectUrl.value && window.open(blobObjectUrl.value)
}

/**
 * @desc 下载气象预警文件
 *
 * **/
function downloadPdf() {
  if (eventDetail.value.fileModels && eventDetail.value.fileModels.length) {
    intelligentApi
      .downloadFile({
        filePath: eventDetail.value.fileModels[0].fileName
      })
      .then(res => {
        file.value = saveAs(res, '气象预警文件.pdf', { type: 'application/pdf' })
      })
  }
}

/**
 * 打开图片
 * @param url
 * */
const onImgClick = url => {
  imgVisible.value = true
  imgUrl.value = url
}

/**
 * @desc 获取高速ai监测文件信息
 * @param  fileModelList  软连接集合
 *
 * **/
function getAIStarm(fileModelList) {
  if (Array.isArray(fileModelList) && fileModelList.length) {
    const proAll = fileModelList.map(i => {
      return new Promise((resolve, reject) => {
        intelligentApi
          .getAIFile({
            name: i.filePath,
            fileType: i.fileContentType
          })
          .then(res =>
            resolve({
              ...res,
              ...i
            })
          )
          .catch(reject)
      })
    })
    Promise.all(proAll).then(result => {
      console.error('result', result)
      fileResourcesList.value = result
        .filter(i => i.data)
        .map(i => ({
          ...i,
          filePath: i.data
        }))
    })
  }
}
</script>

<style scoped lang="less">
/deep/ .mz-panel-content-main {
  padding: 5px 8px;
}

.carousel-item-content {
  width: 100%;
  height: 100%;
  background: #333;
  color: #fff;

  video {
    width: 100%;
    height: 100%;
  }
  img {
    cursor: pointer;
  }
}

.mz-panel.second :deep(.mz-panel-content) {
  padding: 2px;
}

.ant-carousel :deep(.slick-slide) {
  text-align: center;
  height: 160px;
  line-height: 160px;
  // background: #364d79;
  overflow: hidden;

  > div {
    height: 100%;
  }
}

.ant-carousel :deep(.slick-arrow.custom-slick-arrow) {
  width: 17px;
  height: 40px;
  opacity: 0.3;
  background: #000000;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  opacity: 0.8;
  z-index: 1;
}

.ant-carousel :deep(.custom-slick-arrow:before) {
  display: none;
}

.ant-carousel :deep(.custom-slick-arrow:hover) {
  opacity: 0.5;
}

.ant-carousel :deep(.slick-slide h3) {
  color: #fff;
}

.mz-panel-content-main {
  padding-left: 0px !important;
}

.info-confirm-wrapper {
  height: 100%;
  display: flex;
  width: 100%;
  flex-direction: column;
  position: relative;
  background-color: #e6eefc !important;

  /deep/ .info-confirm-center-panel {
    z-index: 10000;

    .mz-panel-content {
      padding: 8px 14px;
    }
  }

  .detail-container {
    width: 100%;
    height: 100%;
    position: relative;

    .detail-content {
      width: 100%;
      height: calc(100% - 50px);

      .box-video {
        width: 100%;
        height: 181px;
        margin-top: 10px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .list-content {
        .row {
          display: flex;
          justify-content: space-between;
          border-bottom: 1px solid #d9e3f4;
          height: 32px;
          align-items: center;
          padding: 5px 1px;

          .text,
          .value {
            font-size: 14px;
          }

          .value {
            max-width: 70%;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }

          .btn-box {
            display: flex;
            margin-top: 6px;

            .view,
            .download {
              padding: 0;
              width: 45px;
              height: 23px;
              border: 1px solid #2671f6;
              color: #2671f6;
              font-size: 14px;
              text-align: center;
              line-height: 21px;
              border-radius: 2px;
              cursor: pointer;
            }

            .download {
              margin-left: 9px;
              border: 1px solid #0099e0;
              color: #0099e0;
            }
          }
        }

        .row.xtsb-img {
          display: flex;
          align-items: center;
          height: auto !important;

          .value-img {
            width: 25px;
            height: 25px;
            margin-left: 5px;
            cursor: pointer;
          }
        }

        .list:last-child {
          border-bottom: none !important;
        }
      }

      .transform-title {
        color: #404040;
        font-size: 14px;
        font-weight: 600;
        margin-top: 10px;
      }

      .transform-switch {
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .transform-button {
          width: 85px;
          height: 30px;
          margin-top: 8px;
          padding: 0;
          text-align: center;
          line-height: 28px;
          color: #929292;
          border: 1px solid #929292;
          cursor: pointer;
        }

        .active {
          color: #266df5;
          border: 1px solid #266df5;
          font-weight: 400;
        }
      }

      .form-item-box {
        display: flex;
        height: 30px;
        line-height: 30px;
        margin-top: 10px;

        .label {
          white-space: nowrap;
          text-align: right;
          width: 70px;
          padding-right: 8px;
        }

        .form-item {
          flex: 1;
          height: 30px;
        }
      }
    }

    .operates-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;

      .operates-content {
        display: flex;
        justify-content: flex-end;
        width: 80%;

        .ant-btn {
          max-width: 80px;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 30px;
          margin-left: 10px;
          border-radius: 3px;
          padding: 0;
        }

        .confirm {
          width: 80px;
          color: #fff;
          background-image: linear-gradient(to right, #298eff, #2564f2);
        }

        .connect {
          width: 80px;

          color: #266df5;
          border: 1px solid #2883fc;
        }

        .misstate {
          width: 60px;
          color: #f1670a;
          border: 1px solid #f1670a;
        }

        .ignore {
          width: 60px;
          color: #e3b21b;
          border: 1px solid #e3b21b;
        }

        .is-disabled {
          color: #00000040;
          border-color: #d9d9d9;
          background: #f5f5f5;
          text-shadow: none;
          box-shadow: none;
        }
      }
    }
  }
}

.textarea {
  resize: none;
  background: #ffffff;
  border: 1px solid #999999;
  border-radius: 4px;

  &::placeholder {
    height: 14px;
    line-height: 14px;
    font-size: 14px;
    font-weight: 500;
    text-align: left;
    color: #999999;
    padding-left: 6px;
    padding-top: 6px;
    color: #999;
  }
}

/deep/.carousel-item-content {
  min-height: 160px !important;
}

.relation-event-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  // box-shadow: 0px 8px 20px 0px rgba(0, 2, 9, 0.4);
}

.loading-box {
  position: absolute;
  background-color: #ecf1fd;
  width: 100%;
  height: 100%;
  display: flex;
  z-index: 100;
}

.tips-model .model-content {
  margin-top: 5px;
}

.footer-buttons {
  height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  justify-content: center;
  margin-top: 8px;

  .model-button {
    width: 80px;
    height: 28px;
    border-radius: 4px;
    background: #ffffff;
    margin: 0 10px;
    padding: 0;
  }

  .model-button.model-confirm {
    border: 1px solid #377ee9;
    color: #266bf4;
  }

  .model-button.model-cancel {
    border: 1px solid #999999;
    border-radius: 4px;
  }
}

.tip-text {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

// .ant-modal-body{

.over-view-img {
  width: 100%;
  height: auto;
  max-height: 84vh;
}

// }
</style>
<style>
.intelligent-model .ant-modal-body {
  padding: 0;
}
</style>
